package community.hospital.service.domain.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import community.hospital.entity.Department;
import community.hospital.entity.request.ListDepartmentRequest;
import community.hospital.mapper.DepartmentMapper;
import community.hospital.service.domain.DepartmentService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static community.hospital.common.Constant.FIRST_LEVEL_DEPARTMENT;
import static community.hospital.common.Constant.STATE_ENABLE;

/**
 * @author yindingjie
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {
    @Override
    public List<Department> listDepartment(ListDepartmentRequest request) {
        Integer state = request.getState();
        Long hospitalId = request.getHospitalId();
        LambdaQueryChainWrapper<Department> wrapper = lambdaQuery();
        //一家医院所有的科室
        List<Department> departmentList = wrapper.eq(state != null, Department::getState, state)
                .eq(hospitalId != null, Department::getHospitalId, hospitalId)
                .orderByDesc(Department::getGmtCreate)
                .list();
        return departmentList;
    }

    @Override
    public int countByDeptName(String deptName) {
        return lambdaQuery().eq(Department::getDeptName, deptName).count().intValue();
    }

    @Override
    public List<Department> listDepartmentByIds(List<Long> ids) {
         return lambdaQuery().in(Department::getPid, ids)
                 .or(t->t.in(Department::getId,ids))
                 .list();
    }

    @Override
    public List<Department> listParentDepartment(ListDepartmentRequest request) {
        return lambdaQuery().eq(request.getHospitalId()!=null,Department::getHospitalId,request.getHospitalId())
                .eq(request.getState()!=null,Department::getState,request.getState())
                .list();

    }

    @Override
    public Boolean updateState(Long id, Integer state) {
        return lambdaUpdate().eq(Department::getId,id).set(Department::getState,state).update();
    }

    @Override
    public List<Department> list1Department() {
        return lambdaQuery().eq(Department::getState, STATE_ENABLE).eq(Department::getPid, 0).list();
    }

    @Override
    public List<Department> listByHospitalId(Long hospitalId) {
        return lambdaQuery().eq(hospitalId!=null,Department::getHospitalId,hospitalId).list();
    }
}
